package com.hgc.ch04.rw;

import java.util.concurrent.CountDownLatch;

/**
 * Created by 01367627 on 2019/7/10.
 */
public class Main {

    private static CountDownLatch latch = new CountDownLatch(13);

    private static class ReadThread extends Thread {
        private IGoodsInfoService goodsInfoService;

        public ReadThread(String name, IGoodsInfoService goodsInfoService) {
            super(name);
            this.goodsInfoService = goodsInfoService;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                goodsInfoService.getNum();
            }
            latch.countDown();
        }
    }

    private static class WriteThread extends Thread {
        private IGoodsInfoService goodsInfoService;

        public WriteThread(String name, IGoodsInfoService goodsInfoService) {
            super(name);
            this.goodsInfoService = goodsInfoService;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                goodsInfoService.setNum(i + 1);
            }
            latch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        GoodsInfo goodsInfo = new GoodsInfo(0, "aaa");
        IGoodsInfoService goodsInfoService = new GoodsInfoServiceRWImpl(goodsInfo);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new ReadThread("R" + i, goodsInfoService).start();
        }
        for (int i = 0; i < 3; i++) {
            new WriteThread("W" + i, goodsInfoService).start();
        }
        latch.await();
        System.out.println("操作完毕耗时" + (System.currentTimeMillis() - start) + "ms");
    }
}
